//
//  AddFireldViewController.m
//  diaoyuren
//
//  Created by Cheng on 16/4/10.
//  Copyright © 2016年 game. All rights reserved.

#import "SayHilloViewController.h"
#import "STInputBar.h"
#import "MyChatCell.h"
#import "OtherChatCell.h"
#import "SpacePagerModel.h"
#import "MyPmModel.h"
#import "MJRefresh.h"
@interface SayHilloViewController ()<DidSendClickedDeleget,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *navTitle;
@property (nonatomic,strong) STInputBar *inputBar;
@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,strong) UIView *backView;
@property (nonatomic,strong) NSMutableArray *dataAry;
@property (nonatomic,strong) MyPmModel *model;
@property (nonatomic,assign) CGFloat Cellhight;
@property (nonatomic,assign) CGFloat CellCount;
@property (nonatomic,assign) BOOL Isresh;
@property (nonatomic,assign) CGFloat contentHeight;
@property (nonatomic,strong) NSMutableDictionary *cellHightDic;
@property (nonatomic,assign) BOOL isContnt;
@end

@implementation SayHilloViewController

-(NSMutableDictionary *)cellHightDic{
    if (!_cellHightDic) {
        _cellHightDic = [NSMutableDictionary dictionary];
    }
    return _cellHightDic;
}

-(NSMutableArray *)dataAry{
    if (!_dataAry) {
        _dataAry = [NSMutableArray array];
    }
    return _dataAry;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.app.myTabBar.tabBar.hidden = YES;
    StatusBlack;
    
    if ([self.type isEqualToString:@"sysm"]) {
        self.navTitle.text = @"意见反馈";
    }

}
- (IBAction)GoBackAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)AchiveDataWhithPage:(NSDictionary *)pageDiac{
    
    [[Manager sharedManager]RequestWhithURL:[NSString stringWithFormat:ChatList,self.otherId] AndParameter:pageDiac AndCompletionType:^(id responseObject, DIEError *error) {
        
        self.model = [[MyPmModel alloc]initWithDictionary:responseObject[@"data"] error:nil];

        NSMutableArray *mutableAry = [NSMutableArray array];
        [mutableAry addObjectsFromArray:self.model.list];
        [mutableAry addObjectsFromArray:self.dataAry];
        self.dataAry = [mutableAry mutableCopy];
        [self.tableview reloadData];
        [self.tableview.header endRefreshing];
    }];
}

-(void)RefreshFooter{
    
    SpacePagerModel *pageModel  = self.model.pager;
    
    if (pageModel.cur_page.integerValue==1) {
        [self.tableview.header endRefreshing];
    }else{
        [self AchiveDataWhithPage:@{@"page":pageModel.prev}];

    }
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.frame = [UIScreen mainScreen].bounds;
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-60) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerNib:[UINib nibWithNibName:@"MyChatCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    [self.tableview registerNib:[UINib nibWithNibName:@"OtherChatCell" bundle:nil] forCellReuseIdentifier:@"Othercell"];
    
    [self.view addSubview:self.tableview];
    self.tableview.showsVerticalScrollIndicator = NO;
    

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(RefreshFooter)];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    header.arrowView.image = nil;
    self.tableview.header = header;
    
    _inputBar = [STInputBar inputBar];

    _backView  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    
    _backView.backgroundColor = TouMingBlack2;
    _backView.alpha = 0;
    [self.view addSubview:_backView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(BackViewTapAction)];
    [_backView addGestureRecognizer:tap];
    
    _inputBar.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, CGRectGetHeight(self.view.bounds)-CGRectGetHeight(_inputBar.frame)+CGRectGetHeight(_inputBar.frame)/2);
    [_inputBar setFitWhenKeyboardShowOrHide:YES];
    _inputBar.deleget = self;
    
    [self.view addSubview:_inputBar];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];//在这里注册通知  观察键盘变化
    
    [self AchiveDataWhithPage:nil];

}

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];// 键盘的frame
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:duration animations:^{
            
            
            if (keyboardF.origin.y==SCREEN_HEIGHT) {//如果键盘隐藏
                
                _backView.alpha = 0;
           
            }else{
            
                _backView.alpha = 1;
            
            }
        }];
    });
}

-(void)BackViewTapAction{

    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
}
#pragma mark---点击发送
-(void)DidSendClicked:(NSString *)sendText{
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    
    
     [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {

            NSDictionary *dic = @{@"touid":self.otherId,@"message":sendText,@"formhash":responseObject[@"data"][@"formhash"]};

            [self SendTextToOtherWhithDic:dic];
        }
    }];

}

-(void)SendTextToOtherWhithDic:(NSDictionary *)dic{

    [[Manager sharedManager]ResponseWhithURL:SendText AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        
        if (!error) {
            if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {

                MyPmListModel *model = [MyPmListModel new];
                model.avatar = self.app.userModel.avatar;
                model.message = dic[@"message"];
                model.myself_tag = @"1";
                
                [self.dataAry addObject:model];
                self.Isresh = NO;
                 [self.tableview reloadData];
               self.inputBar.textView.text = @"";
               
            }else{
                [Manager GetHudWhithText:responseObject[@"message"] AndFatherView:self.view];
            }
        
        }else{
            
            [Manager GetHudWhithText:responseObject[@"网络错误,发送失败"] AndFatherView:self.view];
        }
        
    }];

}


-(NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

        return self.dataAry.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell =  [self tableView:tableView cellForRowAtIndexPath:indexPath];
    if (self.Isresh==NO) {
        self.Isresh=YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       
            if (self.tableview.contentSize.height>_tableview.height) {
                NSIndexPath *indexPath1=[NSIndexPath indexPathForRow:_dataAry.count-1 inSection:0];
                [_tableview scrollToRowAtIndexPath:indexPath1 atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            }
        });
    }
    return 1+cell.height;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    MyPmListModel *model = self.dataAry[indexPath.row];
    if (model.myself_tag.intValue==1) {
        MyChatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.model = model;
        return cell;
    }else{
        OtherChatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Othercell"];
        cell.model = model;
        return cell;
    }
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
@end